package com.example.demo.Interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.Context.BaseContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.parser.Authorization;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

@Slf4j
@Component
public class JWTLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(o instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        HashMap<String, String> map=new HashMap<>();
        String token = httpServletRequest.getHeader("token");
        try {
            log.info("jwt校验:{}", token);
            // 得到DefaultJwtParser
            Claims claims = Jwts.parser()
                    // 设置签名的秘钥
                    .setSigningKey("itheima")
                    // 设置需要解析的jwt
                    .parseClaimsJws(token).getBody();
            log.info("当前员工：" +  claims);
            Long empId = Long.valueOf(claims.get("id").toString());
            BaseContext.setCurrentId(empId);
            return true;
        } catch (Exception exception) {
            log.info("exception: " + exception);
            map.put("msg", "验证失败：" + exception);
        }
        String json = new ObjectMapper().writeValueAsString(map);
        httpServletResponse.setContentType("application/json:charset=UTF=8");
        httpServletResponse.getWriter().println(json);
        return false;
    }
}
